package audit

import (
	"counter-help/admin/server/global"
	"counter-help/admin/server/model/audit"
	auditReq "counter-help/admin/server/model/audit/response"
	"counter-help/admin/server/model/customer"
	"errors"
	"gorm.io/gorm"
)

// TechnicalVerificationService 技术审核服务
type TechnicalVerificationService struct{}
type TechnicalVerificationWithUser struct {
	audit.TechnicalVerification
	customer.CusUser
}

// CreateTechnicalVerification 创建技术审核记录
func (s *TechnicalVerificationService) CreateOrUpdateTechnicalVerification(technicalVerification audit.TechnicalVerification) error {
	var existingVerification audit.TechnicalVerification
	// 检查是否已存在此用户的技术审核记录
	err := global.GVA_DB.Where("user_id = ?", technicalVerification.UserID).First(&existingVerification).Error
	if err == nil {
		// 如果记录存在，执行更新操作
		existingVerification.CompanyName = technicalVerification.CompanyName
		existingVerification.WorkDuration = technicalVerification.WorkDuration
		existingVerification.StatisticalTools = technicalVerification.StatisticalTools
		existingVerification.BusinessDescription = technicalVerification.BusinessDescription
		// 仅当 CertificateImage 不为空时才更新
		if technicalVerification.CertificateImage != "" {
			existingVerification.CertificateImage = technicalVerification.CertificateImage
		}
		existingVerification.IsReviewed = false

		// 更新记录
		return global.GVA_DB.Save(&existingVerification).Error
	} else if errors.Is(err, gorm.ErrRecordNotFound) {
		// 如果记录不存在，执行创建操作
		// 确保 StatisticalTools 被正确存储为 JSON 类型
		return global.GVA_DB.Create(&technicalVerification).Error
	} else {
		// 处理其他错误
		return err
	}
}

// GetTechnicalVerification 获取用户的技术审核记录
func (s *TechnicalVerificationService) GetTechnicalVerification(userID uint) (audit.TechnicalVerification, error) {
	var verification audit.TechnicalVerification
	err := global.GVA_DB.Where("user_id = ?", userID).First(&verification).Error
	return verification, err
}

// ApproveTechnicalVerification 审核通过
func (s *TechnicalVerificationService) ApproveTechnicalVerification(userID uint) error {
	return global.GVA_DB.Model(&audit.TechnicalVerification{}).
		Where("user_id = ?", userID).
		Updates(map[string]interface{}{"is_reviewed": true, "is_approved": true, "rejection_reason": ""}).Error
}

// RejectTechnicalVerification 审核不通过
func (s *TechnicalVerificationService) RejectTechnicalVerification(userID uint, reason string) error {
	return global.GVA_DB.Model(&audit.TechnicalVerification{}).
		Where("user_id = ?", userID).
		Updates(map[string]interface{}{"is_reviewed": true, "is_approved": false, "rejection_reason": reason}).Error
}

//// GetPendingTechnicalVerifications 获取所有未审核的技术审核记录，并手动关联用户信息
//func (s *TechnicalVerificationService) GetPendingTechnicalVerifications() ([]auditReq.TechnicalVerificationResponse, error) {
//	var pendingVerifications []audit.TechnicalVerification
//	err := global.GVA_DB.
//		Where("is_reviewed = ?", false).
//		Find(&pendingVerifications).Error
//	if err != nil {
//		return nil, err
//	}
//
//	var responses []auditReq.TechnicalVerificationResponse
//	for _, verification := range pendingVerifications {
//		var user customer.CusUser
//		if err := global.GVA_DB.Where("id = ?", verification.UserID).First(&user).Error; err != nil {
//			return nil, err
//		}
//		responses = append(responses, convertTechnicalVerificationToResponse(verification, user))
//	}
//	return responses, nil
//}

// 改版后
func (s *TechnicalVerificationService) GetPendingTechnicalVerifications() ([]auditReq.TechnicalVerificationResponse, error) {
	var responsesTechnical []TechnicalVerificationWithUser
	// 使用联合查询
	err := global.GVA_DB.
		Table("technical_verifications").                                        // 指定主表为 user_identities
		Joins("JOIN cus_user ON cus_user.id = technical_verifications.user_id"). // 使用正确的表名
		Where("technical_verifications.is_reviewed = ?", false).
		Select("technical_verifications.*, cus_user.*"). // 选择需要的字段
		Scan(&responsesTechnical).Error                  // 使用 Scan 方法将结果存入 responses
	if err != nil {
		return nil, err
	}
	// 处理转换
	var responses []auditReq.TechnicalVerificationResponse
	for _, identityWithUser := range responsesTechnical {
		responses = append(responses, convertTechnicalVerificationToResponse(identityWithUser.TechnicalVerification, identityWithUser.CusUser))
	}
	return responses, nil
}

//// GetApprovedTechnicalVerifications 获取所有已审核的技术审核记录，并手动关联用户信息
//func (s *TechnicalVerificationService) GetApprovedTechnicalVerifications() ([]auditReq.TechnicalVerificationResponse, error) {
//	var approvedVerifications []audit.TechnicalVerification
//	err := global.GVA_DB.
//		Where("is_reviewed = ?", true).
//		Find(&approvedVerifications).Error
//	if err != nil {
//		return nil, err
//	}
//
//	var responses []auditReq.TechnicalVerificationResponse
//	for _, verification := range approvedVerifications {
//		var user customer.CusUser
//		if err := global.GVA_DB.Where("id = ?", verification.UserID).First(&user).Error; err != nil {
//			return nil, err
//		}
//		responses = append(responses, convertTechnicalVerificationToResponse(verification, user))
//	}
//	return responses, nil
//}

// 改版后
func (s *TechnicalVerificationService) GetApprovedTechnicalVerifications() ([]auditReq.TechnicalVerificationResponse, error) {
	var responsesTechnical []TechnicalVerificationWithUser
	// 使用联合查询
	err := global.GVA_DB.
		Table("technical_verifications").                                        // 指定主表为 user_identities
		Joins("JOIN cus_user ON cus_user.id = technical_verifications.user_id"). // 使用正确的表名
		Where("technical_verifications.is_reviewed = ?", true).
		Select("technical_verifications.*, cus_user.*"). // 选择需要的字段
		Scan(&responsesTechnical).Error                  // 使用 Scan 方法将结果存入 responses
	if err != nil {
		return nil, err
	}
	// 处理转换
	var responses []auditReq.TechnicalVerificationResponse
	for _, identityWithUser := range responsesTechnical {
		responses = append(responses, convertTechnicalVerificationToResponse(identityWithUser.TechnicalVerification, identityWithUser.CusUser))
	}
	return responses, nil
}

// convertTechnicalVerificationToResponse 转换为包含用户信息的响应结构体
func convertTechnicalVerificationToResponse(technical audit.TechnicalVerification, user customer.CusUser) auditReq.TechnicalVerificationResponse {
	return auditReq.TechnicalVerificationResponse{
		TechnicalVerification: technical,
		User:                  user,
	}
}
